//
//  UpgradeMessage.m
//  uteped_sdk
//
//  Created by mateng on 2024/2/20.
//

#import "UpgradeMessage.h"


#define PATH                        @"upgrade"
#define M_START_OTA                 @"startOTA"
#define M_CANCEL_OTA                @"cancelOTA"

#define OTA_STATE_UNKNOWN           ((NSInteger)0)
#define OTA_STATE_TRANSFERRING      ((NSInteger)4)
#define OTA_STATE_TRANSFERRED       ((NSInteger)5)

@implementation UpgradeMessage

- (NSString *)getPath {
    return PATH;
}

- (id)initWithHandler:(UTEPedEventHandler *)handler {
    self = [super initWithHandler:handler];
    if (self) {
        [UTEOTAMgr sharedInstance].delegate = self;
    }
    return self;
}

- (void)otaStateNotify:(NSInteger)errorCode state:(NSInteger)state process:(CGFloat)process {
    __weak typeof(self)weakSelf = self;
    
    process = process * 100;
    
    NSDictionary *data = nil;
    if (state == OTA_STATE_TRANSFERRING) {
        data = [[NSDictionary alloc] initWithObjectsAndKeys:
                PATH, KEY_PATH,
                M_START_OTA, KEY_METHOD,
                @(state), KEY_STATUS,
                @(process), KEY_VALUE, nil];
    } else if (state == OTA_STATE_TRANSFERRED) {
        data = [[NSDictionary alloc] initWithObjectsAndKeys:
                PATH, KEY_PATH,
                M_START_OTA, KEY_METHOD,
                @(state), KEY_STATUS, nil];
    } else {
        data = [[NSDictionary alloc] initWithObjectsAndKeys:
                PATH, KEY_PATH,
                M_START_OTA, KEY_METHOD,
                @(state), KEY_STATUS,
                @(errorCode), KEY_ERROR_CODE, nil];
    }
    
    [weakSelf.eventHander publishEvent:data async:YES];
}

# pragma mark do upgrade
- (BOOL)doUpgrade:(NSString *)filePath {
    __weak typeof(self)weakSelf = self;
    
    BOOL success = NO;
    [[UTEOTAMgr sharedInstance] upgrade:filePath callback:^(NSString *uuid, CGFloat process, NSInteger errorCode, BOOL success) {
        if (errorCode == UTEDeviceErrorNil) {
            if (process >= 1) {
                success = YES;
                [weakSelf otaStateNotify:errorCode state:OTA_STATE_TRANSFERRED process:process];
            } else {
                [weakSelf otaStateNotify:errorCode state:OTA_STATE_TRANSFERRING process:process];
            }
        } else {
            success = NO;
            [weakSelf otaStateNotify:errorCode state:OTA_STATE_UNKNOWN process:process];
        }
    }];
    return success;
}

# pragma mark - methodCallConsumed
- (BOOL) methodCallConsumed:(NSString*)method params:(NSDictionary*)params result:(FlutterResult)result
{
    BOOL consumed = YES;
    if ([super methodCallConsumed:method params:params result:result])
        return YES;
    
    assert(method != nil);
    
    __weak typeof(self)weakSelf = self;
    
    if ([method isEqualToString: M_START_OTA]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSString *filePath = [params objectForKey: KEY_FILE];
        [[SPHelper shareInstance] putObject:@"upgrade_file_path" value:filePath];
        
        BOOL success = [weakSelf doUpgrade:filePath];
        result(@(success));
    } else {
        consumed = NO;
    }
    
    return consumed;
}

- (void)uteForceUpdate:(BOOL)force model:(UTEModelBaseInfo *)model {
    __weak typeof(self)weakSelf = self;
    
    if (force) {
        NSString *filePath = [[SPHelper shareInstance] getObject:@"upgrade_file_path" defaultValue:nil];
        if ([weakSelf otaFileExists:filePath]) {
            NSLog(@"force update: last upgrade file path  %@", filePath);
            [weakSelf doUpgrade:filePath];
        }
    }
}

- (BOOL)otaFileExists:(NSString*)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return filePath != nil && [fileManager fileExistsAtPath:filePath];
}

@end
